package cuit.game.controller;

import cuit.game.entity.User;
import cuit.game.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;


@Controller
public class AuthController {

    @Autowired//注入类
    private UserService userService;

    //登录
    @GetMapping("/login")
    public String login() {return "login";}

    @PostMapping("/auth")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password") String password,
                        HttpServletRequest request) {
        User user= userService.login(username,password);
        if(user!=null){
            // 获取HttpSession对象
            HttpSession session = request.getSession();

            // 将用户ID保存到会话中
            session.setAttribute("user", user);
            return "/index";

        }
        else {
            //redirectAttributes.addFlashAttribute("error", "用户名或密码错误，请重新输入。");
            return "redirect:/login";
        }

    }

    //注册
    @GetMapping("/register")
    public String register() {return "register";}

    @PostMapping("/register")
    public String save(@ModelAttribute("user") User user) {

        userService.save(user);
        return "redirect:/login";
    }
}
